
package cn.sylinx.hbatis.ext.res;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import cn.sylinx.hbatis.io.Resources;
import cn.sylinx.hbatis.log.GLog;

public abstract class ClasspathSqlResourceManager {

	private final static Map<String, String> cache = new HashMap<String, String>();

	public static void clear() {
		synchronized (cache) {
			cache.clear();
		}
	}

	public static String loadAndGet(String sqlpath) {

		InputStream is = null;
		ByteArrayOutputStream baos = null;
		String statement = null;

		try {
			is = Resources.getResourceAsStream(sqlpath);
			if (is != null) {

				baos = new ByteArrayOutputStream();
				int i = -1;
				while ((i = is.read()) != -1) {
					baos.write(i);
				}
				statement = baos.toString();
			}
		} catch (Exception e) {

			GLog.error("sql resource not found: {}", sqlpath);
			statement = null;

		} finally {

			if (is != null) {

				try {
					is.close();
				} catch (IOException e) {
				}
			}

			if (baos != null) {
				try {
					baos.close();
				} catch (IOException e) {
				}
			}
		}

		if (statement != null) {
			cache.put(sqlpath, statement);
		}

		return statement;
	}

	public static String getStatement(String sqlpath) {

		if (cache.containsKey(sqlpath)) {
			GLog.debug("sql bingo: {}", sqlpath);
			return cache.get(sqlpath);
		}

		return loadAndGet(sqlpath);
	}
}
